<?php

namespace Addons\Project\Controller;
use Home\Controller\AddonsController;

class ProjectController extends AddonsController{

    public function lists() {
        $map = [];
        if(I('openid')){
            $map = ['openid'=>I('openid')];
        }
        $top_more_button = [
            [
                'is_button' => true,
                'title' => '导出选中的项目',
                'class' => 'ajax-post location',
                'url' => U('export')
            ],
            [
                'is_buttion' => false,
                'title' => '全部项目',
                'class' => '',
                'url' => U('lists', $map)
            ]
        ];
        foreach(C('PROJECT_STATUS') as $k => $v){
            $top_more_button[] = [
                'title' => $v,
                'url' => U('lists', array_merge(['status'=>$k], $map)),
            ];
        }

        $this->assign('top_more_button', $top_more_button);
        $this->assign ( 'add_button', false );
        $this->assign ( 'del_button', false );
        $this->assign ( 'check_all', true );

        $model = $this->getModel ( 'project' );
        parent::common_lists ( $model );
    }

    public function edit($model = null, $id = 0) {
        is_array ( $model ) || $model = $this->getModel ( $model );
        $templateFile = $this->getAddonTemplate ( $model ['template_edit'] );
        $this->common_edit ( $model, $id, $templateFile );
    }

    /**
     * 导出指定的项目
     * @param $ids
     */
    public function export($ids = null){
        $ids = I('ids');
        if(empty($ids)){
            $this->error('请先选择要导出的项目(点击项目名称左侧的选中框)');
        }
        $lists = M('Project')->where(['id'=>['IN',$ids]])->select();
        if(empty($lists)){
            $this->error('无数据');
        }
        vendor ( 'PHPExcel' );
        vendor ( 'PHPExcel.PHPExcel_IOFactory' );
        vendor ( 'PHPExcel.PHPExcel_Style_Alignment' );
        $objPHPExcel = new \PHPExcel();
        // Set properties
        $objPHPExcel->getProperties()->setCreator("ctos")
            ->setLastModifiedBy("ctos")
            ->setTitle("Office 2007 XLSX Test Document")
            ->setSubject("Office 2007 XLSX Test Document")
            ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
            ->setKeywords("office 2007 openxml php")
            ->setCategory("Test result file");

        //set width
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(10);
        $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(30);

        //设置行高度
        $objPHPExcel->getActiveSheet()->getRowDimension('1')->setRowHeight(22);

        $objPHPExcel->getActiveSheet()->getRowDimension('2')->setRowHeight(20);

        //set font size bold
        $objPHPExcel->getActiveSheet()->getDefaultStyle()->getFont()->setSize(10);
        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getFont()->setBold(true);

        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);
        $objPHPExcel->getActiveSheet()->getStyle('A2:M2')->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);

        //设置水平居中
        $objPHPExcel->getActiveSheet()->getStyle('A1')->getAlignment()->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_CENTER)->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER);

        //合并cell
        $objPHPExcel->getActiveSheet()->mergeCells('A1:M1');

        // set table header content
        $objPHPExcel->setActiveSheetIndex(0)
            ->setCellValue('A1', '项目导出表  时间:'.date('Y-m-d H:i:s'))
            ->setCellValue('A2', '项目名称')
            ->setCellValue('B2', '项目地址')
            ->setCellValue('C2', '建筑面积')
            ->setCellValue('D2', '需求冷量')
            ->setCellValue('E2', '集中供暖')
            ->setCellValue('F2', '用电方式')
            ->setCellValue('G2', '开发商')
            ->setCellValue('H2', '备注')
            ->setCellValue('I2', '申报人')
            ->setCellValue('J2', '申报人联系方式')
            ->setCellValue('K2', '项目状态')
            ->setCellValue('L2', '申报时间')
            ->setCellValue('M2', '原因');

        // Miscellaneous glyphs, UTF-8
        $count = count($lists);
        for($i=0;$i<$count;$i++){
            $objPHPExcel->getActiveSheet(0)->setCellValue('A'.($i+3), $lists[$i]['name']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('B'.($i+3), $lists[$i]['address']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('C'.($i+3), $lists[$i]['area']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('D'.($i+3), $lists[$i]['amount']); //这里调用了common.php的时间戳转换函数
            $objPHPExcel->getActiveSheet(0)->setCellValue('E'.($i+3), C('PROJECT_HEAT')[$lists[$i]['heat']] );
            $objPHPExcel->getActiveSheet(0)->setCellValue('F'.($i+3), C('PROJECT_ELECTRIC')[$lists[$i]['require_time']]);
            $objPHPExcel->getActiveSheet(0)->setCellValue('G'.($i+3), $lists[$i]['developer']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('H'.($i+3), $lists[$i]['remark']);
            $objPHPExcel->getActiveSheet(0)->setCellValue('I'.($i+3), get_nickname_by_openid($lists[$i]['openid']));
            $objPHPExcel->getActiveSheet(0)->setCellValue('J'.($i+3), get_mobile_by_openid($lists[$i]['openid']));
            $objPHPExcel->getActiveSheet(0)->setCellValue('K'.($i+3), C('PROJECT_STATUS')[$lists[$i]['status']]);
            $objPHPExcel->getActiveSheet(0)->setCellValue('L'.($i+3), time_format($lists[$i]['create_time']));
            $objPHPExcel->getActiveSheet(0)->setCellValue('M'.($i+3), $lists[$i]['because']);
            $objPHPExcel->getActiveSheet()->getStyle('A'.($i+3).':M'.($i+3))->getAlignment()->setVertical(\PHPExcel_Style_Alignment::VERTICAL_CENTER)->setHorizontal(\PHPExcel_Style_Alignment::HORIZONTAL_LEFT);
            $objPHPExcel->getActiveSheet()->getStyle('A'.($i+3).':M'.($i+3))->getBorders()->getAllBorders()->setBorderStyle(\PHPExcel_Style_Border::BORDER_THIN);
            $objPHPExcel->getActiveSheet()->getRowDimension($i+3)->setRowHeight(16);
        }


        //  sheet命名
        $objPHPExcel->getActiveSheet()->setTitle('项目导出表');


        // Set active sheet index to the first sheet, so Excel opens this as the first sheet
        $objPHPExcel->setActiveSheetIndex(0);


        // excel头参数
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="项目导出表('.date('Ymd-His').').xls"');  //日期为文件名后缀
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');  //excel5为xls格式，excel2007为xlsx格式
        $objWriter->save('php://output');
    }

    public function getPrint(){
        if(!isset($_GET['id'])){
            $this->error('参数错误');
        }
        $info = M('Project')->where(['id'=>$_GET['id']])->find();
        if(empty($info)){
            $this->error('没有相关数据');
        }
        $userinfo = D('Common/Follow')->getFollowInfoByOpenid($info['openid']);
        $info['nickname'] = $userinfo['nickname'];
        $info['mobile'] = $userinfo['mobile'];
        $info['create_time'] = time_format($info['create_time']);
        $info['status'] = C('PROJECT_STATUS')[$info['status']];
        $info['heat'] = C('PROJECT_HEAT')[$info['heat']];
        $this->success($info);
    }

    public function common_edit($model = null, $id = 0, $templateFile = '') {
        is_array ( $model ) || $model = $this->getModel ( $model );
        $id || $id = I ( 'id' );

        // 获取数据
        $data = M ( get_table_name ( $model ['id'] ) )->find ( $id );
        $data || $this->error ( '数据不存在！' );

        $token = get_token ();
        if (isset ( $data ['token'] ) && $token != $data ['token'] && defined ( 'ADDON_PUBLIC_PATH' )) {
            $this->error ( '非法访问！' );
        }

        if (IS_POST) {
            $Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) );
            // 获取模型的字段信息
            $Model = $this->checkAttr ( $Model, $model ['id'] );
            //添加对于修改状态后的数据给用户发送消息
            $rules = array(
                array('status', 'sendStatus', 2, 'function'),
            );
            $Model->auto($rules);
            if ($Model->create () && $Model->save ()) {
                $this->_saveKeyword ( $model, $id );

                $this->success ( '保存' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'], $this->get_param ) );
            } else {
                $this->error ( $Model->getError () );
            }
        } else {
            $fields = get_model_attribute ( $model ['id'] );
            $temp = array_slice($fields[1], 0, 8);
            $temp['nickname'] = [
                'name' => 'openid',
                'title' => '申报人',
                'disabled' => 1,
                'function' => 'get_nickname_by_openid',
                "is_show" => "1",
                'status' => 1,
                'type' => 'function'
            ];
            $temp['mobile'] = [
                'name' => 'openid',
                'title' => '申报人手机号',
                'disabled' => 1,
                'function' => 'get_mobile_by_openid',
                "is_show" => "1",
                'status' => 1,
                'type' => 'function'
            ];
            $fields[1] = array_merge($temp, array_slice($fields[1], 8));
//            dump($fields);exit;
            $this->assign ( 'fields', $fields );
            $this->assign ( 'data', $data );
            $this->meta_title = '编辑' . $model ['title'];

            $templateFile || $templateFile = $model ['template_edit'] ? $model ['template_edit'] : '';
            $this->display ( $templateFile );
        }
    }
}
